package com.yc.testupload.controller;

import com.yc.testupload.dao.AccountDAO;
import com.yc.testupload.model.Account;
import com.yc.testupload.publisher.PlatformPublisherFactory;
import com.yc.testupload.consumer.BatchPublishConsumer;
import com.yc.testupload.util.RabbitMQConfig;
import com.yc.testupload.service.WechatPublishProducer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.yc.testupload.publisher.PlatformPublisher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 批量发布到多平台的Servlet
 * 负责处理批量发布请求，根据账号类型将任务发送到不同平台
 */
@WebServlet("/api/batch-publish")
public class BatchPublishServlet extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(BatchPublishServlet.class);
    private AccountDAO accountDAO;
    private WechatPublishProducer publishProducer;
    private PlatformPublisherFactory publisherFactory;

    @Override
    public void init() throws ServletException {
        super.init();
        accountDAO = new AccountDAO();
        publishProducer = new WechatPublishProducer();
        publisherFactory = new PlatformPublisherFactory();

        // 启动批量发布消费者线程
        try {
            BatchPublishConsumer publishConsumer = new BatchPublishConsumer();
            Thread consumerThread = new Thread(() -> publishConsumer.start());
            consumerThread.setDaemon(true);
            consumerThread.start();
            logger.info("批量发布消费者线程启动成功");
        } catch (Exception e) {
            logger.error("启动批量发布消费者线程失败: {}", e.getMessage(), e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject resultJson = new JSONObject();

        try {
            // 从session获取用户ID
            HttpSession session = request.getSession();
            if (session == null || session.getAttribute("userId") == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                resultJson.put("code", 1);
                resultJson.put("message", "用户未登录");
                out.write(resultJson.toString());
                return;
            }

            Integer userId = Integer.valueOf(session.getAttribute("userId").toString());
            logger.info("批量发布请求，用户ID: {}", userId);

            // 解析请求体
            StringBuilder jsonBuilder = new StringBuilder();
            String line;
            try (BufferedReader reader = request.getReader()) {
                while ((line = reader.readLine()) != null) {
                    jsonBuilder.append(line);
                }
            }

            JSONObject requestData = new JSONObject(jsonBuilder.toString());
            JSONArray selectedAccountsArray = requestData.getJSONArray("selectedAccounts");
            JSONObject contentData = requestData.getJSONObject("content");

            // 构建选中的账号列表
            List<String> accountIds = new ArrayList<>();
            for (int i = 0; i < selectedAccountsArray.length(); i++) {
                accountIds.add(selectedAccountsArray.getString(i));
            }

            // 获取用户的所有账号
            List<Account> allAccounts = accountDAO.getAccountsByUserId(userId);

            // 过滤出选中的账号
            List<Account> selectedAccounts = allAccounts.stream()
                    .filter(account -> accountIds.contains(String.valueOf(account.getId())))
                    .toList();

            if (selectedAccounts.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resultJson.put("code", 2);
                resultJson.put("message", "未选中有效账号");
                out.write(resultJson.toString());
                return;
            }

            logger.info("开始处理批量发布，选中账号数量: {}", selectedAccounts.size());

            // 按账号类型分组
            Map<String, List<Account>> accountsByType = new HashMap<>();
            for (Account account : selectedAccounts) {
                String type = account.getAccountType();
                accountsByType.computeIfAbsent(type, k -> new ArrayList<>()).add(account);
            }

            // 发送任务到消息队列
            List<String> taskIds = new ArrayList<>();
            for (Map.Entry<String, List<Account>> entry : accountsByType.entrySet()) {
                String platformType = entry.getKey();
                List<Account> platformAccounts = entry.getValue();

                // 根据平台类型获取发布器并发送任务
                PlatformPublisher publisher = publisherFactory.getPublisher(platformType);
                if (publisher != null) {
                    // 构建任务数据
                    Map<String, Object> taskData = new HashMap<>();
                    taskData.put("taskType", "MULTIPLE_ACCOUNTS_PUBLISH");
                    taskData.put("platformType", platformType);
                    taskData.put("userId", userId);
                    taskData.put("content", contentData.toMap());

                    // 添加账号信息
                    JSONArray accountsJson = new JSONArray();
                    for (Account account : platformAccounts) {
                        JSONObject accountJson = new JSONObject();
                        accountJson.put("accountId", account.getId());
                        accountJson.put("accountType", account.getAccountType());
                        accountJson.put("accountName", account.getAccountName());
                        accountJson.put("appId", account.getAccountId());
                        accountJson.put("appSecret", account.getAppSecret());
                        accountsJson.put(accountJson);
                    }
                    taskData.put("accounts", accountsJson.toList());

                    // 发送到消息队列
                    String taskId = publishProducer.sendPublishTask(taskData);
                    taskIds.add(taskId);
                    logger.info("平台 {} 的发布任务已发送到队列，任务ID: {}", platformType, taskId);
                } else {
                    logger.warn("未找到平台类型 {} 的发布器", platformType);
                }
            }

            // 返回成功结果
            resultJson.put("code", 0);
            resultJson.put("message", "批量发布任务已提交");
            resultJson.put("taskIds", taskIds);
            resultJson.put("totalTasks", taskIds.size());
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            logger.error("批量发布处理失败: {}", e.getMessage(), e);
            resultJson.put("code", 500);
            resultJson.put("message", "服务器内部错误: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            out.write(resultJson.toString());
            out.flush();
            out.close();
        }
    }
}